package com.hoppinzq.service.ssh;

import com.hoppinzq.service.bean.SSHBean;
import com.hoppinzq.service.cache.SSHCache;
import com.hoppinzq.service.util.RedisUtils;
import com.hoppinzq.service.util.UUIDUtil;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Vector;

@Component
@Order(1)
public class SSHRunner implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(SSHRunner.class);
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void run(ApplicationArguments args){
        logger.debug("开始预热ssh");
        try {
            SSHCache.zqssh= new SSHBean();
            SSHCache.zqssh.sshRemoteLogin();
            SSHCache.sshMap.put(UUIDUtil.getUUID(),SSHCache.zqssh);
            Session sshSession=SSHCache.zqssh.getSession();
            ChannelSftp channelSftp = (ChannelSftp) sshSession.openChannel("sftp");
            channelSftp.connect();
            String remoteDirPath = "/home/";
            Vector<ChannelSftp.LsEntry> lsEntries = channelSftp.ls(remoteDirPath);
            boolean folderExistsFile = false;
            boolean folderExistsHoppinzq = false;
            for (ChannelSftp.LsEntry entry : lsEntries) {
                if (entry.getFilename().equals("file")) {
                    folderExistsFile = true;
                }
                if (entry.getFilename().equals("hoppinzq")) {
                    folderExistsHoppinzq = true;
                }
            }
            if (!folderExistsFile) {
                channelSftp.mkdir(remoteDirPath+"file");
            }
            if (!folderExistsHoppinzq) {
                channelSftp.mkdir(remoteDirPath+"hoppinzq");
            }
        } catch (Exception e) {
            System.err.println("远程连接失败......");
            e.printStackTrace();
        }
        logger.debug("预热ssh结束");
    }
}